package io.adrainty.bolee.framework.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import io.adrainty.bolee.framework.commons.user.SubjectContentUtil;
import io.adrainty.bolee.framework.commons.user.UserEntity;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/8/4 上午12:08
 */

public class AutoMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        UserEntity userVO = SubjectContentUtil.getUserVO();
        if (userVO != null) {
            this.doFillField(metaObject, "dataDeptNo", userVO.getDeptNo());
            this.doFillField(metaObject, "companyNo", userVO.getCompanyNo());
            this.doFillField(metaObject, "createdBy", userVO.getId());
            this.doFillField(metaObject, "modifiedBy", userVO.getId());
            this.doFillField(metaObject, "createdTime", LocalDateTime.now());
            this.doFillField(metaObject, "modifiedTime", LocalDateTime.now());
            this.doFillField(metaObject, "isDeleted", 0);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserEntity userVO = SubjectContentUtil.getUserVO();
        if (userVO != null) {
            this.strictInsertFill(metaObject, "modifiedBy", Long.class, userVO.getId());
            this.strictInsertFill(metaObject, "modifiedTime", LocalDateTime.class, LocalDateTime.now());
        }
    }

    private void doFillField(MetaObject metaObject, String fieldName, Object fieldVal) {
        if (metaObject.hasSetter(fieldName)) {
            this.setFieldValByName(fieldName, fieldVal, metaObject);
        }
    }

}
